package com.bawei.module_home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.entity.Reply
import com.bawei.lib_common.entity.VideoCommentEntityItem
import com.bawei.lib_image.GlideApp
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_home.R
import com.blankj.utilcode.util.ToastUtils

/**
 * 视频评论列表适配器
 */
class VideoCommentListAdapter constructor(
    private val list: MutableList<VideoCommentEntityItem>,
    var onItemLongClick: ((position: Int) -> Unit)? = null,
    var onItemLoveClick: ((position: Int) -> Unit)? = null
    ):BaseExpandableListAdapter() {
    
//    private val commentLikeManager = CommentLikeManager.getInstance(BaseApplication.instance)
    private var currentClickedCommentId: Int = -1
    
    override fun getGroupCount(): Int = list.size

    override fun getChildrenCount(groupPosition: Int): Int = list[groupPosition].replyList.size

    override fun getGroup(groupPosition: Int): VideoCommentEntityItem = list[groupPosition]

    override fun getChild(groupPosition: Int, childPosition: Int): Reply = list[groupPosition].replyList[childPosition]

    override fun getGroupId(groupPosition: Int): Long = list[groupPosition].id.toLong()

    override fun getChildId(groupPosition: Int, childPosition: Int): Long = list[groupPosition].replyList[childPosition].id.toLong()

    override fun hasStableIds(): Boolean = true
    override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean = true

    /**
     * 一级评论
     */
    override fun getGroupView(groupPosition: Int, childPosition: Boolean, converView: View?, parent: ViewGroup?): View {
        var groupEntity = list[groupPosition]
        val holder:GroupViewHolder
        val view:View
        if (converView == null){
            view = LayoutInflater.from(parent?.context).inflate(R.layout.item_comment_lever_one,parent,false)
            holder = GroupViewHolder(view)
            view.tag = holder
        }else{
            view = converView
            holder = (converView.tag as GroupViewHolder)
        }
        GlideApp.with(BaseApplication.instance).load(groupEntity.userlogo).placeholder(R.drawable.comment_icon).into(holder.tvImage)
        //设置文本信息
        holder.apply {
            holder.tvName.text = if (groupEntity.nickname.isNullOrEmpty()) "小财神" else groupEntity.nickname
            holder.tvContent.text = if (groupEntity.nickname.isNullOrEmpty()) "上点击发送酷酷酷" else groupEntity.content
            
            // 设置点赞数量
            holder.tvLikeCount.text = groupEntity.agreenum.toString()
            
            // 检查并设置点赞状态
//            updateLikeStatus(holder, groupEntity.id)
            
            var tvExpand:TextView = view.findViewById(R.id.tv_expand1)
            if (groupEntity.replyList.isNotEmpty()){
                tvExpand.visibility = View.VISIBLE
                tvExpand.text = if (childPosition) "----收起回复----" else "----展开回复----"
            }else{
                tvExpand.visibility = View.GONE
            }
            oneItem.setOnLongClickListener {
                if (groupEntity.userid == AuthMMKV.uId){
                    onItemLongClick?.invoke(groupPosition)
                }else{
                    ToastUtils.showLong("请勿删除别人的评论")
                }
                true
            }
            tvLove.setOnClickListener {
                onItemLoveClick?.invoke(groupPosition)
            }
        }
        return  view

    }
    
    /**
     * 更新点赞状态UI
     */
//    private fun updateLikeStatus(holder: GroupViewHolder, commentId: Int) {
//        // 在协程中检查数据库中的点赞状态
//        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
//            try {
//                val isLiked = commentLikeManager.isCommentLikedByUser(commentId, AuthMMKV.uId)
//                val localLikeCount = commentLikeManager.getLocalLikeCount(commentId)
//
//                // 更新UI
//                holder.tvLove.setImageResource(
//                    if (isLiked) R.drawable.ic_love_24_filled
//                    else R.drawable.ic_love_24
//                )
//
//                // 更新点赞数量（优先显示本地数量，如果没有则显示服务器数量）
//                val comment = list.find { it.id == commentId }
//                val displayCount = if (localLikeCount > 0) localLikeCount else (comment?.agreenum ?: 0)
//                holder.tvLikeCount.text = displayCount.toString()
//            } catch (e: Exception) {
//                // 处理异常，使用默认状态
//                holder.tvLove.setImageResource(R.drawable.ic_love_24)
//                val comment = list.find { it.id == commentId }
//                holder.tvLikeCount.text = (comment?.agreenum ?: 0).toString()
//            }
//        }
//    }
    
    /**
     * 更新评论的点赞状态（供外部调用）
     */
//    fun updateCommentLikeStatus(commentId: Int, isLiked: Boolean) {
//        val position = list.indexOfFirst { it.id == commentId }
//        if (position != -1) {
//            // 更新数据库
//            if (isLiked) {
//                commentLikeManager.likeComment(commentId, AuthMMKV.uId)
//            } else {
//                commentLikeManager.unlikeComment(commentId, AuthMMKV.uId)
//            }
//
//            // 通知适配器更新UI
//            notifyDataSetChanged()
//        }
//    }
    
    /**
     * 设置当前点击的评论ID
     */
    fun setCurrentClickedCommentId(commentId: Int) {
        currentClickedCommentId = commentId
    }
    
    /**
     * 获取当前点击的评论ID
     */
    fun getCurrentClickedCommentId(): Int {
        return currentClickedCommentId
    }
    
    inner class  GroupViewHolder(view: View){
        var tvName:TextView = view.findViewById(R.id.comment_name)
        var tvContent:TextView = view.findViewById(R.id.comment_content)
        var tvImage:ImageView = view.findViewById(R.id.commit_iv)
        var oneItem: ConstraintLayout = view.findViewById(R.id.comment_one)
        var tvLove:ImageView = view.findViewById(R.id.commit_iv_love)
        var tvLikeCount:TextView = view.findViewById(R.id.comment_num)
    }

    /**
     * 二级评论
     */
    override fun getChildView(groupPosition: Int, childPasition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup?): View {
        var groupEntity = list[groupPosition].replyList[childPasition]
        val holder:GroupViewHolder
        val view:View
        if (convertView == null){
            view = LayoutInflater.from(parent?.context).inflate(R.layout.item_comment_lever_two,parent,false)
            holder = GroupViewHolder(view)
            view.tag = holder
        }else{
            view = convertView
            holder = (convertView.tag as GroupViewHolder)
        }
        GlideApp.with(BaseApplication.instance).load(groupEntity.userlogo).placeholder(R.drawable.comment_icon).into(holder.tvImage)
        //设置文本信息
        holder.apply {
            holder.tvName.text = if (groupEntity.nickname.isNullOrEmpty()) "小财神" else groupEntity.nickname
            holder.tvContent.text = if (groupEntity.nickname.isNullOrEmpty()) "上点击发送酷酷酷" else groupEntity.content
        }
        return  view
    }


}